package com.zgh.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class SmsClient {

	private static final Logger logger=LoggerFactory.getLogger(SmsClient.class);

	private static String smsSvcUrl="http://119.23.134.102:8860";	//服务器URL 地址
	private static String cust_code="200091";	//账号
	private static String password="JWTFTC5UFH";	//密码
	private static String sp_code="115312351";		//接入码（扩展码）
	private static String owner="【厦门市总工会】";		//短信前缀，必须加

	private  static Map<String,String> map=new HashMap<String,String>();	//错误码及错误信息
	static{
		map.put("-1","未知错误");
		map.put("0","成功");
		map.put("1","消息结构错");
		map.put("2","非法源IP地址");
		map.put("3","认证错误");
		map.put("4","协议版本错误");
		map.put("6","短信内容超过规定的长度");
		map.put("8","流量控制错，超出最高流量");
		map.put("12","用户账号未登录");
		map.put("13","目标号码在黑名单中");
		map.put("15","通道不支持");
		map.put("22","客户账号已经被关闭");
		map.put("23","客户账号状态错误");
		map.put("24","客户账号余额不足");
		map.put("25","内容包含敏感词");
		map.put("26","模版过滤失败");
		map.put("27","长短信拆分条数过多");
		map.put("28","模版过滤失败");
		map.put("29","错误号码");
	}


	public static String sendSms(String mobiles, String content){
		return sendSms(mobiles, content, sp_code, 0);
	}

	public static String sendSms(String mobiles, String content, long task_id){
		return sendSms(mobiles, content, sp_code, task_id);
	}

	public static String sendSms(String mobiles, String content, String sp_code){
		return sendSms(mobiles, content, sp_code, 0);
	}

	public static String sendSms(String mobiles, String content, String sp_code,
			long task_id)  {
		content=owner+content;
		try{
			String urlencContent = URLEncoder.encode(content,"utf-8");
			//String sign = MD5.getMD5((urlencContent + password).getBytes());
	        String sign=MD5.sign(urlencContent, password, "utf-8");
			String postData = "content=" + urlencContent + "&destMobiles="
					+ mobiles + "&sign=" + sign + "&cust_code=" + cust_code
					+ "&sp_code=" + sp_code + "&task_id=" + task_id;
			URL myurl = new URL(smsSvcUrl);
			URLConnection urlc = myurl.openConnection();
			urlc.setReadTimeout(1000 * 30);
			urlc.setDoOutput(true);
			urlc.setDoInput(true);
			urlc.setAllowUserInteraction(false);

			DataOutputStream server = new DataOutputStream(urlc.getOutputStream());


			server.write(postData.getBytes("utf-8"));
			server.close();

			BufferedReader in = new BufferedReader(new InputStreamReader(
					urlc.getInputStream(), "utf-8"));
			String resXml = "", s = "";
			while ((s = in.readLine()) != null)
				resXml = resXml + s + "\r\n";
			in.close();
			return getCode(mobiles,content,URLDecoder.decode(resXml,"utf-8"));
		}catch(Exception ex){
			logger.error(ex.getMessage(),ex);
			return "0";
		}


	}

	private static String getCode(String mobile,String content,String returnStr){
		//记录发送短信的日志
    	StringBuffer sb=new StringBuffer();
    	sb.append(mobile).append("$").append(content).append("$").append(System.currentTimeMillis());
    	//返回1表示成功，其他表示失败

		if(returnStr.startsWith("SUCCESS")){
			String str=returnStr.split(":")[3].trim();
			if("0".equals(str)){
				sb.append("$").append("1").append("$").append("成功");
				//记录日志
				return "1";
			}
			sb.append("$").append("0").append("$").append(map.get(str));
			//记录日志
			logger.error(mobile+"短信发送错误："+map.get(str));
			if("13".equals(str) || "29".equals(str)){
				return str;
			}else{
				return "0";
			}
		}else{
			sb.append("$").append("0").append("$").append(returnStr.substring(6));
			//记录日志
			logger.error(mobile+"短信发送失败："+returnStr.substring(6));
			return "0";
		}
	}
	
	public static int getValidTime(){
		return 5;
	}
	
	public static int getSendInterval(){
		return 1;
	}
}
